package cn.tedu.coolshark.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {
    //配置文件地址
    @Value("${dirPath}")
    private String dirPath;

    @RequestMapping("/upload")
    public String upload(MultipartFile pic) throws IOException {
        //得到唯一文件名
        String fileName=pic.getOriginalFilename();
        /*获取文件后缀名*/
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;
        //准备保存图片的文件夹
        //String dirPath="d:/files";
        File dirFile=new File(dirPath);
        /*判断文件是否存在*/
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //把图片保存到指定的文件夹下面  抛出异常
        String filePath=dirPath+"/"+fileName;
        pic.transferTo(new File(filePath));
        return "/"+fileName;
    }
    /*删除*/
    @RequestMapping("/remove")
    public void remove(String url){
        new File(dirPath+url).delete();
    }

}
